import { ref, reactive } from "vue";
import { testFormConfig, validateForm } from "../form-config";

/**
 * 测试单据信息专用 Composable
 */
export function useTestInfo() {
  // 表单数据
  const formData = reactive<Record<string, any>>({
    materialName: "",
    keyMaterialName: "",
  });

  // 表单错误
  const formErrors = ref<Record<string, string>>({});

  // 选择器值（这里用不到，但保持接口一致性）
  const pickerValues = reactive<Record<string, any>>({});

  /**
   * 验证单个字段
   */
  const validateField = (fieldKey: string) => {
    const field = testFormConfig[fieldKey];
    if (!field) return;

    const value = formData[fieldKey];

    // 清除之前的错误
    delete formErrors.value[fieldKey];

    // 必填字段验证
    if (field.required && !value) {
      formErrors.value[fieldKey] = `请输入${field.label}`;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        formErrors.value[fieldKey] = field.patternErrorMessage || `${field.label}格式不正确`;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        formErrors.value[fieldKey] = result.message;
        return;
      }
    }
  };

  /**
   * 验证所有字段
   */
  const validateAllFields = () => {
    const result = validateForm(formData);
    formErrors.value = result.errors;
    return result.valid;
  };

  /**
   * 验证所有字段并返回详细信息
   */
  const validateAllFieldsWithDetails = () => {
    const result = validateForm(formData);
    formErrors.value = result.errors;

    // 获取第一个错误信息
    const firstErrorMessage = Object.values(result.errors)[0] || "";

    return {
      valid: result.valid,
      errors: result.errors,
      firstErrorMessage
    };
  };

  /**
   * 模拟提交（静态版本）
   */
  const submitForm = async (): Promise<{
    success: boolean;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 模拟提交成功
    console.log("提交的表单数据:", formData);

    return {
      success: true,
      validation: validationResult
    };
  };

  return {
    // 表单数据和状态
    formData,
    formErrors,
    pickerValues,

    // 验证方法
    validateField,
    validateAllFields,
    validateAllFieldsWithDetails,

    // 提交方法
    submitForm,
  };
}
